package com.ews.onlineexchange.rest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.transaction.Transactional;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;

import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import com.alibaba.fastjson.JSONObject;

//import org.jboss.resteasy.plugins.providers.multipart.InputPart;
//import org.jboss.resteasy.plugins.providers.multipart.MultipartFormDataInput;

import com.ews.onlineexchange.app.AppService;
import com.ews.onlineexchange.app.RatedTradeListForApp;
import com.ews.onlineexchange.app.entity.ServiceSupplierBasicInfo;
import com.ews.onlineexchange.app.entity.SimpleTradeTradeRating;
import com.ews.onlineexchange.app.entity.TempBusiness;
import com.ews.onlineexchange.app.entity.TempQualificationCert;
import com.ews.onlineexchange.app.entity.TempServiceSupplier;
import com.ews.onlineexchange.controller.ServiceSupplierExporter;
import com.ews.onlineexchange.controller.ServiceSupplierHome;
import com.ews.onlineexchange.model.ServiceSupplier;
import com.ews.onlineexchange.model.Trade;
import com.ews.onlineexchange.service.ServiceSupplierService;
import com.ews.onlineexchange.util.DateUtil;
import com.ews.onlineexchange.util.WorkBookUtil;


@Path(value = "/serviceSupplier")
@Transactional
public class ServiceSupplierRest {
	@Inject
	EntityManager entityManager;
	@Inject
	AppService appService;
	@Inject
	ServiceSupplierHome serviceSupplierHome;
	private static final String SERVER_UPLOAD_LOCATION_FOLDER = "D:/Upload_Files/";
	@GET
	@Path("/getServiceSupplierBasicInfoById/{id}")
	@Produces("application/json")
	@Context
	public ServiceSupplierBasicInfo getServiceSupplierBasicInfoById(@PathParam("id") String id)  {
		serviceSupplierHome.setId(id);
		ServiceSupplier supplier = serviceSupplierHome.getInstance();
		ServiceSupplierBasicInfo serviceSupplierBasicInfo = appService.getServiceSupplierBasicInfo(supplier);
		return serviceSupplierBasicInfo;
	}
	
	@GET
	@Path("/getServiceSupplierBusinessesInfoById/{id}")
	@Produces("application/json")
	@Context
	public List<TempBusiness> getServiceSupplierBusinessesInfoById(@PathParam("id") String id)  {
		serviceSupplierHome.setId(id);
		ServiceSupplier supplier = serviceSupplierHome.getInstance();
		List<TempBusiness> businesses = appService.getServiceSupplierBusinesses(supplier);
		return businesses;
		
	}
	
	@GET
	@Path("/getServiceSupplierCertsById/{id}")
	@Produces("application/json")
	@Context
	public List<TempQualificationCert> getServiceSupplierCertsById(@PathParam("id") String id)  {
		serviceSupplierHome.setId(id);
		ServiceSupplier supplier = serviceSupplierHome.getInstance();
		List<TempQualificationCert> certs = appService.getServiceSupplierCerts(supplier);
		return certs;
		
	}
	
	@Inject
	RatedTradeListForApp ratedTradeListForApp;
	
	@GET
	@Path("/getPublicServiceSupplierInfo/{id}")
	@Produces("application/json")
	@Context
	public TempServiceSupplier getServiceSupplierFullInfo(@PathParam("id") String id)  {
		serviceSupplierHome.setId(id);
		ServiceSupplier supplier = serviceSupplierHome.getInstance();
		TempServiceSupplier serviceSupplier = appService.getPublicServiceSupplierFullInfo(supplier);
		ratedTradeListForApp.refresh();
       
        ratedTradeListForApp.setMaxResults(null);
        ratedTradeListForApp.setApp_userId(id);
        List<Trade> tradeList = ratedTradeListForApp.getResultList();
        List<SimpleTradeTradeRating> sBulletinTradeList = appService.getSimpleTradeRatingList(tradeList);
        serviceSupplier.setRatedTradeList(sBulletinTradeList);
		return serviceSupplier;
	}
//	
	@POST
	@Path("/updateServiceSupplier")
	@Produces(MediaType.APPLICATION_JSON)
	public Response  updateServiceSupplier(@FormParam("name") String name) {
		 	
		
	        return Response.status(200).entity(name).build();
	}
	
//	@POST
//    @Path("/upload")
//    @Consumes("multipart/form-data")
//    public Response uploadFile(MultipartFormDataInput input) {
//        String fileName = "";
//        Map<String, List<InputPart>> formParts = input.getFormDataMap();
//        List<InputPart> inPart = formParts.get("file");
//        for (InputPart inputPart : inPart) {
//             try {
//                MultivaluedMap<String, String> headers = inputPart.getHeaders();
//                fileName = parseFileName(headers);
//                InputStream istream = inputPart.getBody(InputStream.class,null);
//                fileName = SERVER_UPLOAD_LOCATION_FOLDER + fileName;
//                saveFile(istream,fileName);
//              } catch (IOException e) {
//                e.printStackTrace();
//              }
//            }
//                String output = "File saved to server location : " + fileName;
//        return Response.status(200).entity(output).build();
//    }
//
//	
//	 private String parseFileName(MultivaluedMap<String, String> headers) {
// 	        String[] contentDispositionHeader = headers.getFirst("Content-Disposition").split(";");
// 	        for (String name : contentDispositionHeader) {
// 	            if ((name.trim().startsWith("filename"))) {
// 	                String[] tmp = name.split("=");
// 	                String fileName = tmp[1].trim().replaceAll("\"","");
// 	                return fileName;
// 	            }
// 	        }
// 	        return "randomName";
// 	    }
//	
//	 private void saveFile(InputStream uploadedInputStream, String serverLocation) {
// 	        try {
// 	            OutputStream outpuStream = new FileOutputStream(new File(serverLocation));
// 	            int read = 0;
// 	            byte[] bytes = new byte[1024];
// 	            outpuStream = new FileOutputStream(new File(serverLocation));
// 	            while ((read = uploadedInputStream.read(bytes)) != -1) {
// 	                outpuStream.write(bytes, 0, read);
// 	            }
// 	            outpuStream.flush();
// 	            outpuStream.close();
// 	        } catch (IOException e) {
// 	            e.printStackTrace();
// 	        }
// 	    }
	@Inject
	ServiceSupplierService serviceSupplierService;
	@GET
	@Path("/getServiceSupplierStat")
	@Produces("application/json")
	@Context
	public JSONObject getServiceSupplierFullInfo(@QueryParam("pageSize") Integer pageSize, @QueryParam("pageNumber") Integer pageNumber,
			@QueryParam("startDate") String startDate,@QueryParam("endDate") String endDate,@QueryParam("qualificationClassId") String qualificationClassId,
			@QueryParam("sectorId") String sectorId,@QueryParam("childSectorId") String childSectorId)  {
			if(pageSize == null) pageSize = 5;
			if(pageNumber == null) pageNumber = 1;
			initDateParam(startDate, endDate);
			JSONObject json =  serviceSupplierService.stat(pageSize, pageNumber, sDate, eDate, qualificationClassId, sectorId, childSectorId);
			
			return json;
			
		
	}
	@Inject
	ServiceSupplierExporter serviceSupplierExporter;
	@GET    
    @Produces(MediaType.APPLICATION_OCTET_STREAM)
	@Path( value = "/supplierContactsExport" )
	public Response exportBulletinStats( ) throws IOException {
		String fileName = "东营市网上中介超市中介机构联络单.xlsx";
		Workbook workbook = serviceSupplierExporter.export();
		File tempFile = File.createTempFile("ONLINEEXCHANGE", "TEMPFILE");
		if(!tempFile.exists()) {
			tempFile.createNewFile();
		}
		FileOutputStream fileOut = new FileOutputStream(tempFile);
		workbook.write(fileOut);		
		workbook.close();
		ResponseBuilder response = Response.ok( tempFile );
		response.header("Content-Disposition", "attachment;filename="+new String(fileName.getBytes(),"ISO8859-1"));
		return response.build();
	}
	
	private Date sDate;
	private Date eDate;
	public void initDateParam(String startingDate,String endingDate) {
		if(org.apache.commons.lang3.StringUtils.isNotBlank(startingDate)) {
			try {
				sDate = DateUtil.getDate(startingDate);
			} catch (Exception e) {
				// TODO: handle exception
			}
		}
		if(org.apache.commons.lang3.StringUtils.isNotBlank(endingDate)) {
			try {
				Date tempDate = DateUtil.getDate(endingDate);
				if(tempDate != null) {
					Calendar cal = Calendar.getInstance();
					cal.setTime(tempDate);
					cal.set(Calendar.HOUR_OF_DAY, 23);
					cal.set(Calendar.MINUTE, 59);
					cal.set(Calendar.SECOND, 59);
					this.eDate = cal.getTime();
				}
				sDate = DateUtil.getDate(startingDate);
			} catch (Exception e) {
				// TODO: handle exception
			}
		}
	}

	public Date getsDate() {
		return sDate;
	}

	public void setsDate(Date sDate) {
		this.sDate = sDate;
	}

	public Date geteDate() {
		return eDate;
	}

	public void seteDate(Date eDate) {
		this.eDate = eDate;
	}
	
}
